package array;

/**
 * 处理旋转矩阵，顺时针旋转90度
 * 思路：
 * 1. 先按对角线镜像对称
 * 2. 再对每一行进行翻转
 */
public class RotationMatrix {

    public void rotate(int[][] matrix) {
        int n = matrix.length;
        // 先按对角线镜像对称
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                // 交换matrix[i][j]和matrix[j][i]
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }

        // 再对每一行进行翻转
        for (int[] row : matrix) {
            reverse(row);
        }
    }

    private void reverse(int[] row) {
        int i = 0, j = row.length - 1;
        while (i < j) {
            int temp = row[i];
            row[i] = row[j];
            row[j] = temp;
            i++;
            j--;
        }
    }
}
